package com.atguigu.gmall.redisson;

import com.atguigu.gmall.common.consts.RedisConst;
import com.google.common.hash.BloomFilter;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.redisson.client.RedisClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * @Author 卡尼奶
 * @Date 2022/5/24 16:58
 * @Version 1.0
 */
@Slf4j
@AutoConfigureAfter(RedisAutoConfiguration.class) //必须在redis自动配置之后再执行
@Configuration
public class AppRedissonAutoConfiguration {

    @Autowired(required = false)
    private List<BloomTask> bloomTask;

    @Bean
    public RedissonClient redissonClient(RedisProperties redisProperties){
        Config config = new Config();
        config.useSingleServer().setAddress("redis://"+redisProperties.getHost()+":"+redisProperties.getPort())
                .setPassword(redisProperties.getPassword());
        RedissonClient client = Redisson.create(config);
        return client;
    }

    /**
     * 注入Bloom过滤器
     * @param redissonClient
     * @return
     */
    @Bean
    public RBloomFilter<Object> bloomFilter(RedissonClient redissonClient){
        RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter(RedisConst.BLOOM_SKU_ID);
        if (bloomFilter.isExists()) {
            log.info("Redis已经配置好了布隆...");
            return bloomFilter;
        }
        log.info("Redis没有配置好布隆...，正在配置");
        bloomFilter.tryInit(5000000,0.0000001);

        //初始化数据
        for (BloomTask task : bloomTask) {
            if (task instanceof SkuBloomTask){
                task.initData(bloomFilter);
            }
        }
        return bloomFilter;
    }
}
